package com.njtoyo.taxi.admin.service.local_service.commodity.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.mapper.master.entity.GeoDriverRegionArea;
import com.njtoyo.taxi.admin.mapper.master.entity.local_service.*;
import com.njtoyo.taxi.admin.mapper.master.mapper.GeoDriverRegionAreaMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.local_service.*;
import com.njtoyo.taxi.admin.rest.presenter.local_service.commodity.IsPresentedPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.isPresented.IsPresentedAddWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.isPresented.IsPresentedPageWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.isPresented.IsPresentedUpdateWrapper;
import com.njtoyo.taxi.admin.service.local_service.commodity.IsPresentedService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.util.ObjectUtil.isEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;
import static java.util.stream.Collectors.toList;

@Service
@Slf4j
public class IsPresentedServiceImpl implements IsPresentedService {

    @Autowired
    private LifeMerchantCommodityMapper lifeMerchantCommodityMapper;

    @Autowired
    private LifeDriverRegionCommodityMappingMapper lifeDriverRegionCommodityMappingMapper;

    @Autowired
    private GeoDriverRegionAreaMapper driverRegionAreaMapper;

    @Autowired
    private GeoMerchantRegionAreaMapper merchantRegionAreaMapper;

    @Autowired
    private GeoMerchantRegionMapper merchantRegionMapper;

    @Autowired
    private LifeMerchantMapper lifeMerchantMapper;

    @Autowired
    private LifeMerchantCommodityMapper commodityMapper;


    /**
     * 赠送商品列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<IsPresentedPresenter>> getPage(AdminUser adminUser, IsPresentedPageWrapper wrapper) {
        switch (adminUser.getAccountType()) {
            case platform:
                break;
            default:
                return RestResult.failed("账号权限不够");
        }
        Page<IsPresentedPresenter> page = lifeDriverRegionCommodityMappingMapper.getPage(wrapper);
        List<IsPresentedPresenter> list = page.getRecords();
        if (isNotEmpty(list)) {
            List<Long> commodityIds = list.stream().map(IsPresentedPresenter::getCommodityId).collect(toList());
            List<Long> merchantIds = list.stream().map(IsPresentedPresenter::getMerchantId).collect(toList());
            List<Long> merchantRegionIds = list.stream().map(IsPresentedPresenter::getMerchantRegionId).collect(toList());

            QueryWrapper<LifeMerchantCommodity> commodityQueryWrapper = new QueryWrapper<>();
            commodityQueryWrapper.in("id", commodityIds);
            List<LifeMerchantCommodity> commodities = lifeMerchantCommodityMapper.selectList(commodityQueryWrapper);

            QueryWrapper<LifeMerchant> lifeMerchantQueryWrapper = new QueryWrapper<>();
            lifeMerchantQueryWrapper.in("id", merchantIds);
            List<LifeMerchant> merchantList = lifeMerchantMapper.selectList(lifeMerchantQueryWrapper);

            //商户运营区
            QueryWrapper<GeoMerchantRegion> regionQueryWrapper = new QueryWrapper<>();
            regionQueryWrapper.in("id", merchantRegionIds);
            List<GeoMerchantRegion> merchantRegions = merchantRegionMapper.selectList(regionQueryWrapper);

            Map<Long, List<LifeMerchant>> mcollect =
                    merchantList.stream().collect(Collectors.groupingBy(interval -> interval.getId()));

            Map<Long, List<LifeMerchantCommodity>> collect =
                    commodities.stream().collect(Collectors.groupingBy(interval -> interval.getId()));

            list.forEach(isPresentedPresenter -> {
                Long commodityId = isPresentedPresenter.getCommodityId();
                Long merchantId = isPresentedPresenter.getMerchantId();
                Long merchantRegionId = isPresentedPresenter.getMerchantRegionId();
                List<LifeMerchantCommodity> orDefault = collect.getOrDefault(commodityId, null);
                isPresentedPresenter.setLifeMerchantCommodity(orDefault);

                List<LifeMerchant> morDefault = mcollect.getOrDefault(merchantId, null);
                isPresentedPresenter.setLifeMerchants(morDefault);
                isPresentedPresenter.setLifeMerchantCommodity(orDefault);

                //商户运营区名称
                merchantRegions.forEach(merchantRegion -> {
                    Long id = merchantRegion.getId();
                    if (merchantRegionId.equals(id)) {
                        isPresentedPresenter.setMerchantName(merchantRegion.getName());
                    }
                });

            });
        }
        return RestResult.success(page);
    }

    /**
     * 赠送商品添加
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult add(AdminUser adminUser, IsPresentedAddWrapper wrapper) {
        //唯一规则(区域下可赠送商品唯一)
        Long driverRegionId = wrapper.getDriverRegionId();
        Long commodityId = wrapper.getCommodityId();
        String imageUrl = wrapper.getImageUrl();
        Long merchantId = wrapper.getMerchantId();
        //life_driver_region_commodity_mapping
        QueryWrapper<LifeDriverRegionCommodityMapping> commodityMappingQueryWrapper = new QueryWrapper<>();
        commodityMappingQueryWrapper.eq("driver_region_id", driverRegionId);
        commodityMappingQueryWrapper.eq("commodity_id", commodityId);
        Integer count = lifeDriverRegionCommodityMappingMapper.selectCount(commodityMappingQueryWrapper);
        if (count > 0) {
            return RestResult.failed("同一运营区规则只能配置一个赠送商品");
        }

        try {
            getObjectRestResult(driverRegionId, commodityId, merchantId);
        } catch (Exception e) {
            return RestResult.failed(e.getMessage());
        }
        LifeDriverRegionCommodityMapping lifeDriverRegionCommodityMapping = new LifeDriverRegionCommodityMapping();
        lifeDriverRegionCommodityMapping.setDriverRegionId(driverRegionId);
        lifeDriverRegionCommodityMapping.setCommodityId(commodityId);
        lifeDriverRegionCommodityMapping.setImageUrl(imageUrl);
        lifeDriverRegionCommodityMapping.setMerchantId(merchantId);
        lifeDriverRegionCommodityMappingMapper.insert(lifeDriverRegionCommodityMapping);
        Long id = lifeDriverRegionCommodityMapping.getId();
        log.info("添加赠送商品规则 {}", id);
        return RestResult.success();
    }

    /**
     * 赠送商品修改
     *
     * @param id
     * @param wrapper
     * @return
     */
    @Override
    public RestResult update(Long id, IsPresentedUpdateWrapper wrapper) {
        LifeDriverRegionCommodityMapping lifeDriverRegionCommodityMapping = lifeDriverRegionCommodityMappingMapper.selectById(id);
        if (isEmpty(lifeDriverRegionCommodityMapping)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        //唯一规则(区域下可赠送商品唯一)
        Long driverRegionId = wrapper.getDriverRegionId();
        Long commodityId = wrapper.getCommodityId();
        String imageUrl = wrapper.getImageUrl();
        Long merchantId = wrapper.getMerchantId();

        //修改
        if (lifeDriverRegionCommodityMapping.getDriverRegionId().equals(driverRegionId) && lifeDriverRegionCommodityMapping.getCommodityId().equals(commodityId)) {
          log.info("修改赠送商品时与本身相同");
        } else {
            QueryWrapper<LifeDriverRegionCommodityMapping> commodityMappingQueryWrapper = new QueryWrapper<>();
            commodityMappingQueryWrapper.eq("driver_region_id", driverRegionId);
            commodityMappingQueryWrapper.eq("commodity_id", commodityId);
            Integer count = lifeDriverRegionCommodityMappingMapper.selectCount(commodityMappingQueryWrapper);
            if (count > 0) {
                return RestResult.failed("同一运营区规则只能配置一个赠送商品");
            }
        }
        try {
            getObjectRestResult(driverRegionId, commodityId, merchantId);
        } catch (Exception e) {
            return RestResult.failed(e.getMessage());
        }

        new LambdaUpdateChainWrapper<>(lifeDriverRegionCommodityMappingMapper)
                .eq(LifeDriverRegionCommodityMapping::getId, id)
                .set(LifeDriverRegionCommodityMapping::getDriverRegionId, driverRegionId)
                .set(LifeDriverRegionCommodityMapping::getCommodityId, commodityId)
                .set(LifeDriverRegionCommodityMapping::getImageUrl, imageUrl)
                .set(LifeDriverRegionCommodityMapping::getMerchantId, merchantId)
                .set(LifeDriverRegionCommodityMapping::getUpdatedAt, new Date())
                .update();
        log.info("修改赠送商品规则 {}", id);
        return RestResult.success();
    }

    /**
     * 赠送商品删除
     *
     * @param id
     * @return
     */
    @Override
    public RestResult delete(Long id) {
        LifeDriverRegionCommodityMapping lifeDriverRegionCommodityMapping = lifeDriverRegionCommodityMappingMapper.selectById(id);
        if (isEmpty(lifeDriverRegionCommodityMapping)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        lifeDriverRegionCommodityMappingMapper.deleteById(id);
        log.info("删除赠送商品规则 {}", id);
        return RestResult.success();
    }


    /**
     * 验证是否唯一
     *
     * @param driverRegionId
     * @param commodityId
     * @return
     */
    private void getObjectRestResult(Long driverRegionId, Long commodityId, Long merchantId) {

        //商品不能赠送
        LifeMerchantCommodity lifeMerchantCommodity = lifeMerchantCommodityMapper.selectById(commodityId);
        if (isNotEmpty(lifeMerchantCommodity)) {
            Boolean isPresented = lifeMerchantCommodity.getIsPresented();
            if (!isPresented) {
                throw new RuntimeException("商品不是赠送商品");
            }
            if (!lifeMerchantCommodity.getMerchantId().equals(merchantId)) {
                throw new RuntimeException("商品不是该商户下的商品");
            }
        }

        //司机运营区->area->geo_merchant_region_area->商户->可赠送商品
        QueryWrapper<GeoDriverRegionArea> driverRegionAreaWrapper = new QueryWrapper<>();
        driverRegionAreaWrapper.select("area_id");
        driverRegionAreaWrapper.in("driver_region_id", driverRegionId);
        List<GeoDriverRegionArea> geoDriverRegionAreas = driverRegionAreaMapper.selectList(driverRegionAreaWrapper);
        if (isNotEmpty(geoDriverRegionAreas)) {
            List<Long> areaIds = geoDriverRegionAreas.stream().map(GeoDriverRegionArea::getAreaId).collect(toList());

            //商户运营区
            QueryWrapper<GeoMerchantRegionArea> merchantRegionWrapper = new QueryWrapper<>();
            merchantRegionWrapper.select("merchant_region_id");
            merchantRegionWrapper.in("area_id", areaIds);
            List<GeoMerchantRegionArea> regionAreaList = merchantRegionAreaMapper.selectList(merchantRegionWrapper);


            if (isNotEmpty(regionAreaList)) {
                List<Long> merchantRegionIds = regionAreaList.stream().map(GeoMerchantRegionArea::getMerchantRegionId).collect(toList());

                //商户id
                QueryWrapper<LifeMerchant> merchantWrapper = new QueryWrapper<>();
                merchantWrapper.select("id");
                merchantWrapper.in("merchant_region_id", merchantRegionIds);
                List<LifeMerchant> merchantList = lifeMerchantMapper.selectList(merchantWrapper);

                if (isNotEmpty(merchantList)) {
                    List<Long> merchantIds = merchantList.stream().map(LifeMerchant::getId).collect(toList());

                    //可赠送商品
                    QueryWrapper<LifeMerchantCommodity> commodityWrapper = new QueryWrapper<>();
                    commodityWrapper.select("id");
                    commodityWrapper.eq("is_presented", true);
                    commodityWrapper.in("merchant_id", merchantIds);
                    List<LifeMerchantCommodity> commodities = commodityMapper.selectList(commodityWrapper);
                    List<Long> ids = commodities.stream().map(LifeMerchantCommodity::getId).collect(toList());

                    boolean flag = ids.contains(commodityId);
                    if (!flag) {
                        throw new RuntimeException("同一运营区规则没有这个可赠送商品");
                    }
                }
            }
        }
    }


}
